package com.qf.exception;

import com.qf.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@Slf4j
public class MyExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object expcetionHandler(HttpServletRequest request, Exception e){
        log.error("[exception handler] 发生异常！", e);
        //如果是href、form的提交，异常发生后，返回错误页面
        //如果是ajax提交，异常发生后，返回R对象

        String requestWith = request.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(requestWith)) {
            //发送的ajax请求
            return new R().setCode(R.CODE.ERROR).setMsg("服务器繁忙，请稍后再试！");
        }

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("myerror");

        return modelAndView;
    }
}
